package com.currency.mall.ui.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.ValueCallback;
import android.widget.TextView;

import com.currency.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2019/1/3.
 */

public class WebViewActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    private WebFragment mWebFragment;
    private Fragment mCurrentFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        Intent intent = this.getIntent();
        String mPath = intent.getStringExtra("ExtraWebPath");
        String mTitle = intent.getStringExtra("ExtraWebTitle");
        mWebFragment = WebFragment.newInstance(mPath, mTitle);
        mCurrentFragment = mWebFragment;
        if (savedInstanceState == null) {
            FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            ft.add(R.id.container, mCurrentFragment).commit();
        }
        tvTitle.setText(mTitle);
    }

    @OnClick(R.id.ll_back)
    public void onViewClicked() {
        goback();
    }

    public void goback() {
        if(mWebFragment!=null){
            if ((mWebFragment).canGoBack()) {
                String url =  mWebFragment.getWebView().getUrl();
                mWebFragment.getWebView().evaluateJavascript("javascript:backToURL()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        if(TextUtils.isEmpty(value) || "null".equals(value)){
                            (mWebFragment).goBack();// 返回前一个页面
                        }else{
                            try {
                                int s = value.length();
                                String url = value.substring(1, s - 1);
                                mWebFragment.getWebView().loadUrl(url);
                            } catch (Exception e) {
                                (mWebFragment).goBack();// 返回前一个页面
                            }
                        }
                    }
                });
            }else{
                finish();
            }
        }
    }
}
